﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Oracle.ManagedDataAccess.Client;
using System.Net.Http;

namespace HundSunDBQryServer
{
    internal class Program
    {
        public static List<User> users;
        static int TimerTickNum = 1000 * 60;
        public static Dictionary<string, User> tokenUserDic = new Dictionary<string, User>();
        static void Main(string[] args)
        {
            ProtProxy.StartCmd("netsh interface portproxy add v4tov4 listenport=12366 listenaddress=0.0.0.0 connectport=1521 connectaddress=10.16.76.70");
            string users_str = ConfigurationManager.AppSettings.Get("users");
            if (users_str==null)
            {
                Console.WriteLine("账户未配置,自动配置默认账户：admin，123456");
                users = new List<User>();
                users.Add(new User() 
                {
                    UserID = "admin",
                    Password = "123456",
                });
                UpdateSetting("users", JsonConvert.SerializeObject(users));
            }
            else
            {
                users=JsonConvert.DeserializeObject<List<User>>(users_str);
            }
            Thread.CurrentThread.IsBackground = true;
            //wireguard
            
            WireguardCli.start();


            //wireguard

            Console.WriteLine($"柜台资金流水查询服务");
            // 读取配置项
            string portValue = ConfigurationManager.AppSettings["Port"];
            if (portValue == null)
            {
                portValue = "12360";
                UpdateSetting("Port", portValue);
            }
            MyHttpServer httpserver = new MyHttpServer(int.Parse(portValue));
            Console.WriteLine($"web端口：{portValue}");

            //Console.WriteLine($"[GET] /QryFundJour");
            httpserver.listen();
            Task.Run(() =>
            {
                while (true)
                {
                    TimerTick();
                    Thread.Sleep(TimerTickNum);
                }
            });
            while (true)
            {
                var cmd = Console.ReadLine();
                if (cmd == "exit")
                {
                    break;
                }
            }
            
        }
        public static void UpdateSetting(string key, string value)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection settings = configuration.AppSettings.Settings;

            if (settings[key] == null)
            {
                settings.Add(key, value);
            }
            else
            {
                settings[key].Value = value;
            }

            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name);
        }
        static void TimerTick() 
        {
            var itime = DateTime.Now.TimeOfDay;
            var hisholdTime= new TimeSpan(15,30,00);
            if (TimeSpan.Compare(itime, hisholdTime)>0)
            {

            }
        }
        static bool PostHisHold(string TradingDay) 
        {
            bool rebool=false;
            using (HttpClient client = new HttpClient())
            {
                List<Dictionary<string, string>> rsp = new List<Dictionary<string, string>>();
                string sql = $"select t.init_date,t.client_id,t.futu_code,t.futucode_type,t.entrust_bs,t.current_amount/t.amount_per_hand hand,t.futu_exch_type from HS_HIS.HIS_FUHOLDSINFOSUM t where t.init_date='{TradingDay}' and t.current_amount>0";
                // 设置Oracle数据库连接字符串
                string connectionString = "User Id=hs_user;Password=hundsun;Data Source=//10.16.76.70:1521/nuf20bk;";
                // 创建Oracle连接对象
                using (OracleConnection connection = new OracleConnection(connectionString))
                {
                    try
                    {
                        // 打开数据库连接
                        connection.Open();
                        OracleCommand command = connection.CreateCommand();
                        command.CommandText = sql;
                        var records = SqlHelp.getRecords(command);
                        foreach (var r in records)
                        {
                            try
                            {
                                Dictionary<string, string> data = new Dictionary<string, string>();
                                foreach (var item in r)
                                {
                                    data.Add(item.Key, item.Value.ToString());
                                }
                                rsp.Add(data);
                            }
                            catch (Exception)
                            {
                                Console.WriteLine(JsonConvert.SerializeObject(r));
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error connecting to Oracle database: " + ex.StackTrace);
                    }
                }
                if (rsp.Count > 0)
                {
                    string str = JsonConvert.SerializeObject(rsp);
                    HttpContent content = new StringContent(str);
                    var res = client.PostAsync("http://122.224.27.51:12360/hisHold", content).Result;
                    rebool = true;
                }
            }
            return rebool;
        }
        
    }
}
